package ct.zxd.wxpay;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.SortedMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ct.zxd.db.OrderDao;

/**
 * Servlet implementation class HandleWXPayCallBackServlet
 */
public class HandleWXPayCallBackServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	/**
     * key
     * */
    private static final String key = "ZHIXINGQIANLIzhiyunhuicui6270220";
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
//		 System.out.println("进入buy方法");
	        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
	        String line = null;
	        StringBuilder sb = new StringBuilder();
	        while((line = br.readLine()) != null){
	            sb.append(line);
	        }
	        br.close();
	        //sb为微信返回的xml
	        String notityXml = sb.toString();
	        String resXml = "";
	        Map map = null;
	        try {
	        	map = XmlUtil.doXMLParse(notityXml);
			} catch (Exception e) {
				e.printStackTrace();
				response.getWriter().write("微信支付返回结果校验错误");
			}
	        
	        System.out.println("map = " + map);
	        String returnCode = (String) map.get("return_code");
	        try{
	            if("SUCCESS".equals(returnCode)){ //判断是否处理过
	                //进行签名验证，看是否是从微信发送过来的,防止资金被盗
	                SortedMap stringStringMap = PayUtil.paraFilter(map);
//	                String signMy = PayUtil.createSign("utf-8", stringStringMap, MapUtils.getString(configProperties, "mah_password"));
	                String signMy = PayUtil.createSign("utf-8", stringStringMap, key);
	                
	                System.out.println("signMy = " + signMy);
	                System.out.println("flag = " + map.get("sign"));
	                
	                String out_trade_no=(String) map.get("out_trade_no");
                    String [] strings = out_trade_no.split("-");
                    int orderid = Integer.parseInt(strings[1]);
                    OrderDao dao = new OrderDao();
                    
	                if(signMy.equals(map.get("sign"))){

	                	//更改订单状态为已付款
	                    dao.updateOrderStatus(orderid, "1", 2);
	                   
		                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
		                        + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
		            }else {
		            	//更改订单状态为异常
		            	dao.updateOrderStatus(orderid, "1", 9);
		            	
		                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"	
		                        + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
		            }
	            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
	            out.write(resXml.getBytes()); //告诉微信服务器,我收到了,不要再回调action方法了
	            out.flush();
	            out.close();
	        }}catch (Exception e){
	            e.printStackTrace();
	        }

	        
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
